package com.example.shgt;

// 引入必要的类
import com.bumptech.glide.Glide;
import com.example.shgt.entity.GoodsData;

import android.content.Intent;
import android.content.SharedPreferences;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast; // 导入Toast类
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.io.IOException;
import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Headers;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class DetailsActivity extends AppCompatActivity {
    // 定义 Gson 实例
    private final Gson gson = new Gson();

    // 定义UI组件
    private TextView textPrice;
    private TextView textTypeName;
    private TextView textContent;
    private TextView textAddr;
    private ImageView goodsImage;
    private Button buyButton; // 定义购买按钮
    private Button lianxiButton;//定义联系商家按钮

    private long productId;

    private SharedPreferences sharedPreferences;

    // 用于存储卖家ID
    private String sellerId;


    // 定义OkHttpClient为成员变量，避免重复创建
    private OkHttpClient client = new OkHttpClient();

    // 记录当前购买价格
    private int currentPurchaseAmount = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // 设置布局
        setContentView(R.layout.details_page);

        // 初始化控件
        textPrice = findViewById(R.id.goods_price); // 获取价格
        textTypeName = findViewById(R.id.goods_type); // 获取类型
        textContent = findViewById(R.id.goods_content);
        textAddr = findViewById(R.id.goods_addr);
        goodsImage = findViewById(R.id.goods_image);
        buyButton = findViewById(R.id.buy_button); // 获取购买按钮
        lianxiButton = findViewById(R.id.lianxi_button);//获取联系卖家按钮

        // 初始化 SharedPreferences
        sharedPreferences = getSharedPreferences("UserPrefs", MODE_PRIVATE);

        // 获取当前登录用户的userId作为buyerId
        String buyerId = sharedPreferences.getString("userId", "");
        if (buyerId.isEmpty()) {
            // 用户未登录，跳转到登录页面
            Toast.makeText(this, "用户未登录，请先登录", Toast.LENGTH_SHORT).show();
            Intent intent = new Intent(DetailsActivity.this, LoginActivity.class);
            startActivity(intent);
            finish();
            return;
        }

        // 获取 Intent 中传递的 productId
        productId = getIntent().getLongExtra("id", -1); // 默认值为 -1

        // 检查 productId 是否有效
        if (productId != -1) {
            // 通过 productId 获取商品详情
            getProductDetails(String.valueOf(productId)); // 将 productId 转换为字符串传递
        } else {
            Toast.makeText(this, "无效的商品ID", Toast.LENGTH_SHORT).show();
        }

        // 设置购买按钮点击事件
        buyButton.setOnClickListener(v -> {
            if (sellerId == null || sellerId.isEmpty()) {
                Toast.makeText(this, "卖家信息缺失，无法购买", Toast.LENGTH_SHORT).show();
                return;
            }
            // 获取buyerId
            String buyerIdFromPrefs = sharedPreferences.getString("userId", "");
            if (buyerIdFromPrefs.isEmpty()) {
                Toast.makeText(this, "用户ID缺失，请重新登录", Toast.LENGTH_SHORT).show();
                return;
            }
            // 获取购买价格
            int price = getPriceFromTextView();
            if (price <= 0) {
                Toast.makeText(this, "无效的购买价格", Toast.LENGTH_SHORT).show();
                return;
            }
            // 更新当前购买金额
            currentPurchaseAmount = price;
            // 调用购买方法
            buyProduct(String.valueOf(productId), buyerIdFromPrefs, sellerId, price);
        });


        lianxiButton.setOnClickListener(v -> {
                    Intent intent = new Intent(this, MessageDetailActivity.class);
                    intent.putExtra("sellerId", sellerId); // 传递卖家ID
                    startActivity(intent);

        });
    }

    /**
     * 获取商品详情
     */
    private void getProductDetails(String goodsId) {
        // url路径
        String url = "https://api-store.openguet.cn/api/member/tran/goods/details?goodsId=" + goodsId;

        // 请求头
        Headers headers = new Headers.Builder()
                .add("appId", "479dbe79299a4653ada0432942111871")
                .add("appSecret", "14687c6d2cc860b264339b1d93bf409f2bb6c")
                .add("Accept", "application/json, text/plain, */*")
                .build();

        // 请求组合创建
        Request request = new Request.Builder()
                .url(url)
                .headers(headers)
                .get()
                .build();

        try {
            // 发起请求，传入callback进行回调
            client.newCall(request).enqueue(productCallback);
        } catch (Exception ex) {
            ex.printStackTrace();
            runOnUiThread(() -> {
                Toast.makeText(DetailsActivity.this, "网络错误，请稍后重试", Toast.LENGTH_SHORT).show();
            });
        }
    }

    /**
     * 获取商品详情的回调
     */
    private final Callback productCallback = new Callback() {
        @Override
        public void onFailure(@NonNull Call call, IOException e) {
            // 在主线程中更新UI
            runOnUiThread(() -> {
                Toast.makeText(DetailsActivity.this, "请求失败: " + e.getMessage(), Toast.LENGTH_LONG).show();
            });
            // 打印异常 stack trace
            e.printStackTrace();
        }

        @Override
        public void onResponse(@NonNull Call call, Response response) throws IOException {
            // 获取HTTP状态码
            int httpStatusCode = response.code();
            Log.d("info", "HTTP Status Code: " + httpStatusCode);

            // 检查请求是否成功
            if (response.isSuccessful()) {
                // 获取响应体的json串
                String body = response.body().string();
                Log.d("info", body);

                // 解析json串到自己封装的状态
                Type jsonType = new TypeToken<ResponseBody<GoodsData>>() {}.getType();
                ResponseBody<GoodsData> dataResponseBody = gson.fromJson(body, jsonType);

                // 获取业务逻辑状态码
                int businessStatusCode = dataResponseBody.getCode();
                Log.d("info", "Business Status Code: " + businessStatusCode);

                // 根据业务状态码进一步处理
                if (businessStatusCode == 200) {
                    // 请求成功，处理 dataResponseBody.getData()
                    GoodsData goodsData = dataResponseBody.getData();
                    // 获取卖家ID，假设GoodsData类中有sellerId字段（这里是tUserId）
                    sellerId = String.valueOf(goodsData.getTUserId()); // 根据API响应，tUserId是卖家ID

                    // 在主线程中更新UI
                    runOnUiThread(() -> {
                        textContent.setText("详情: " + goodsData.getContent());
                        textAddr.setText("发货地: " + goodsData.getAddr());
                        textPrice.setText("价格: " + goodsData.getPrice());
                        textTypeName.setText("类型: " + goodsData.getTypeName());

                        // 检查 imageUrlList 是否为空
                        List<String> imageUrlList = goodsData.getImageUrlList();
                        if (imageUrlList != null && !imageUrlList.isEmpty()) {
                            // 加载图片
                            Glide.with(DetailsActivity.this)
                                    .load(imageUrlList.get(0)) // 获取列表中的第一张图片
                                    .into(goodsImage);
                        } else {
                            // 处理没有图片的情况
                            goodsImage.setImageResource(R.drawable.baseline_disabled_by_default_24); // 使用默认图像
                            Log.d("info", "No image available");
                        }
                    });

                } else {
                    // 业务层面错误，处理 msg
                    String msg = dataResponseBody.getMsg();
                    Log.d("info", msg);
                    runOnUiThread(() -> {
                        Toast.makeText(DetailsActivity.this, "获取商品详情失败: " + msg, Toast.LENGTH_SHORT).show();
                    });
                }
            } else {
                // 请求失败，处理状态码
                Log.d("info", "请求失败，状态码: " + httpStatusCode);
                // 在主线程中更新UI
                runOnUiThread(() -> Toast.makeText(DetailsActivity.this, "请求失败，HTTP状态码: " + httpStatusCode, Toast.LENGTH_LONG).show());
            }
        }
    };

    /**
     * 购买商品的方法
     */
    private void buyProduct(String goodsId, String buyerId, String sellerId, int price) {
        Log.d("DetailsActivity", "调用购买接口，商品ID: " + goodsId + ", 买家ID: " + buyerId + ", 卖家ID: " + sellerId + ", 价格: " + price);
        new Thread(() -> {
            // url路径
            String url = "https://api-store.openguet.cn/api/member/tran/trading";

            // 请求头
            Headers headers = new Headers.Builder()
                    .add("appId", "479dbe79299a4653ada0432942111871")
                    .add("appSecret", "14687c6d2cc860b264339b1d93bf409f2bb6c")
                    .add("Accept", "application/json, text/plain, */*")
                    .add("Content-Type", "application/json")
                    .build();

            // 请求体，使用JSON格式
            Map<String, String> bodyMap = new HashMap<>();
            bodyMap.put("buyerId", buyerId);
            bodyMap.put("goodsId", goodsId);
            bodyMap.put("price", String.valueOf(price));
            bodyMap.put("sellerId", sellerId);

            String jsonBody = gson.toJson(bodyMap);
            MediaType MEDIA_TYPE_JSON = MediaType.parse("application/json; charset=utf-8");
            RequestBody requestBody = RequestBody.create(MEDIA_TYPE_JSON, jsonBody);

            // 请求组合创建
            Request request = new Request.Builder()
                    .url(url)
                    .headers(headers)
                    .post(requestBody) // 发送 POST 请求
                    .build();

            try {
                // 发起请求，传入callback进行回调
                client.newCall(request).enqueue(purchaseCallback);
            } catch (Exception ex) {
                ex.printStackTrace();
                runOnUiThread(() -> {
                    Toast.makeText(DetailsActivity.this, "购买请求失败，请检查网络或稍后重试", Toast.LENGTH_SHORT).show();
                });
            }
        }).start();
    }

    /**
     * 购买商品的回调
     */
    private final Callback purchaseCallback = new Callback() {
        @Override
        public void onFailure(@NonNull Call call, IOException e) {
            runOnUiThread(() -> {
                Toast.makeText(DetailsActivity.this, "购买失败: " + e.getMessage(), Toast.LENGTH_LONG).show();
            });
            e.printStackTrace();
        }

        @Override
        public void onResponse(@NonNull Call call, Response response) throws IOException {
            if (response.isSuccessful()) {
                // 获取响应体的json串
                String body = response.body().string();
                Log.d("info", body);

                // 解析json串到自己封装的状态，假设data为字符串
                Type jsonType = new TypeToken<ResponseBody<String>>() {}.getType();
                ResponseBody<String> dataResponseBody = gson.fromJson(body, jsonType);

                // 获取业务逻辑状态码
                int businessStatusCode = dataResponseBody.getCode();
                Log.d("info", "Business Status Code: " + businessStatusCode);

                if (businessStatusCode == 200) {
                    // 请求成功，处理 dataResponseBody.getData()
                    String msg = dataResponseBody.getData();

                    runOnUiThread(() -> {
                        Toast.makeText(DetailsActivity.this, "购买成功: " + msg, Toast.LENGTH_SHORT).show();

                        // 更新 SharedPreferences 中的余额
                        int currentBalance = sharedPreferences.getInt("money", 0);
                        int newBalance = currentBalance - currentPurchaseAmount;
                        if (newBalance < 0) {
                            newBalance = 0; // 防止余额为负
                        }
                        SharedPreferences.Editor editor = sharedPreferences.edit();
                        editor.putInt("money", newBalance);
                        editor.apply();

                        // 发送广播通知余额已更新，以便其他组件（如MineFragment）刷新显示
                        Intent intent = new Intent("com.example.shgt.BALANCE_UPDATED");
                        sendBroadcast(intent);
                    });
                } else {
                    // 业务层面错误，处理 msg
                    String msg = dataResponseBody.getMsg();
                    Log.d("info", msg);
                    runOnUiThread(() -> {
                        Toast.makeText(DetailsActivity.this, "购买失败: " + msg, Toast.LENGTH_SHORT).show();
                    });
                }
            } else {
                // 请求失败，处理状态码
                int httpStatusCode = response.code();
                Log.d("info", "购买请求失败，HTTP状态码: " + httpStatusCode);
                runOnUiThread(() -> {
                    Toast.makeText(DetailsActivity.this, "购买失败，HTTP状态码: " + httpStatusCode, Toast.LENGTH_LONG).show();
                });
            }
        }
    };

    /**
     * 从textPrice TextView中解析价格
     */
    private int getPriceFromTextView() {
        String priceText = textPrice.getText().toString().replace("价格: ", "").trim();
        try {
            return Integer.parseInt(priceText);
        } catch (NumberFormatException e) {
            Log.e("DetailsActivity", "无法解析价格: " + priceText);
            return 0;
        }
    }

    /**
     * 通用响应体类
     */
    public static class ResponseBody<T> {
        private int code;
        private String msg;
        private T data;

        public int getCode() {
            return code;
        }

        public String getMsg() {
            return msg;
        }

        public T getData() {
            return data;
        }

        @NonNull
        @Override
        public String toString() {
            return "ResponseBody{" +
                    "code=" + code +
                    ", msg='" + msg + '\'' +
                    ", data=" + data +
                    '}';
        }
    }
}


